package com.warm.system.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import com.warm.core.constant.Constants;
import com.warm.core.domain.AjaxResult;
import com.warm.core.domain.R;
import com.warm.pom.satoken.utils.LoginUtils;
import com.warm.select.api.orm.domain.sys.SysMenu;
import com.warm.select.api.orm.domain.sys.SysUser;
import com.warm.system.api.model.LoginBody;
import com.warm.system.service.ISysMenuService;
import com.warm.system.service.SysLoginService;
import com.warm.system.service.SysPermissionService;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.validation.annotation.Valid;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author warm
 */
@Valid
@Controller
public class SysLoginController {
    @Inject
    private SysLoginService loginService;

    @Inject
    private ISysMenuService menuService;

    @Inject
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @Post
    @Mapping("/login")
    public AjaxResult login(LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @Get
    @Mapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = LoginUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @Get
    @Mapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = LoginUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 登出
     *
     * @param ctx
     * @return
     */
    @SaIgnore
    @Mapping("logout")
    public R<Void> logout(Context ctx) {
        loginService.logout(ctx);
        return R.ok();
    }
}
